<?php
include_once("cache.func.php");
include_once("bussion.func.php");
include_once("push.func.php");
include_once("coupon.func.php");
include_once("aliyun.oss.func.php");
include_once ("rsaEncrypt.func.php");
if (!function_exists('get_client_ip')) {
    /**
     * 获取客户端IP地址
     * @param int $type 返回类型 0 返回IP地址 1 返回IPV4地址数字
     * @param bool $adv 是否进行高级模式获取（有可能被伪装）
     * @return mixed
     */
    function get_client_ip($type = 0, $adv = true)
    {
        $type = $type ? 1 : 0;
        static $ip = NULL;
        if ($ip !== NULL) return $ip[$type];
        if ($adv) {
            if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
                $arr = explode(',', $_SERVER['HTTP_X_FORWARDED_FOR']);
                $pos = array_search('unknown', $arr);
                if (false !== $pos) unset($arr[$pos]);
                $ip = trim($arr[0]);
            } elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
                $ip = $_SERVER['HTTP_CLIENT_IP'];
            } elseif (isset($_SERVER['REMOTE_ADDR'])) {
                $ip = $_SERVER['REMOTE_ADDR'];
            }
        } elseif (isset($_SERVER['REMOTE_ADDR'])) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        // IP地址合法验证
        $long = sprintf("%u", ip2long($ip));
        $ip = $long ? array($ip, $long) : array('0.0.0.0', 0);
        return $ip[$type];
    }
}


function changeImageSize($pic, $width = 800, $height = 600)
{
    //
    if (empty($width)) {
        $width = 800;
    }
    if (empty($height)) {
        $height = 600;
    }
    $stmp = explode(".", $pic);

    $extensions = strtolower($stmp[1]);
    if ($extensions == "jpg" || $extensions == "jpeg" || $extensions == "png") {
        //图片路径
        $way = ROOT_PATH . 'public' . $pic;


        //缩略图路径
        $smallway = ROOT_PATH . 'public' . $stmp[0] . "_1." . $stmp[1];


        $image = \think\Image::open($way);// 按照原图的比例生成一个最大为150*150的缩略图并保存为thumb.jpg
        $small = $image->thumb($width, $height, \think\Image::THUMB_CENTER)->save($smallway);
        $pic = $stmp[0] . "_1." . $stmp[1];
    }

    //
    return $pic;
}


/**
 * curl get形式访问地址
 * @param $url url地址
 *
 * @return mixed
 */
function get_api_data($url)
{
    //初始化
    $curl = curl_init();
    //设置抓取的url
    curl_setopt($curl, CURLOPT_URL, $url);
    //设置头文件的信息作为数据流输出
    curl_setopt($curl, CURLOPT_HEADER, 0);
    //设置获取的信息以文件流的形式返回，而不是直接输出。
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    //执行命令
    $data = curl_exec($curl);
    //关闭URL请求
    curl_close($curl);
    return $data;
}

/**
 * curl post带数据访问地址
 * @param $url url地址
 * @param $param post数据
 *
 * @return mixed
 */
function get_url($url, $param = array())
{

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if (!empty($param)) {
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($param));
    }
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_TIMEOUT, 20);
    $response = curl_exec($ch);
    curl_close($ch);
    // echo $url.'?'.http_build_query($param);
    return $response;
}

function makeImportData($adb, $title)
{
    $data = array();

    foreach ($adb as $key => $val) {
        $temp = array();
        foreach ($val as $k => $v) {
            $temp[$title[$k]] = $v;
        }
        $data[] = $temp;
    }
    return $data;
}

function parseExcel($file, $where = array(), $limit = array(0, 1000))
{
    $title = array();
    $import_file_type = array(
        'xlsx' => 'Excel2007',
        'xls' => 'Excel5',
    );
    error_reporting(E_ALL); //open error
    set_time_limit(0); // script time out
    include_once(dirname(realpath(APP_PATH)) . "/vendor/PHPExcel/PHPExcel/IOFactory.php");
    $pathinfo = pathinfo($file);
    if (!isset($import_file_type[$pathinfo['extension']])) {
    } else {
        $inputFileType = $import_file_type[$pathinfo['extension']];
    }

    $inputFileName = $file;
    try {
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);//set format
        $objPHPExcel = $objReader->load($inputFileName);//loading file
        $objWorksheet = $objPHPExcel->getSheet(0);
        //$objWorksheet = $objPHPExcel->getActiveSheet();//get count rows
        $highestRow = $objWorksheet->getHighestRow();//get count rows
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//all count cols
    } catch (Exception $e) {
        return array('err' => 1);
    }

    $start_index = $limit[0] + 1;
    $end_index = $limit[1] + $start_index;
    $headtitle = array();
    $list = array();

    for ($row = 1; $row <= $highestRow; $row++) {
        $strs = array();
        if ($row == 1) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $cell_val = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                if ($row == 1) {
                    if (!$cell_val) {
                        break;
                    }
                }
                $strs[$col] = $cell_val;
            }
            $title = $strs;
        } elseif ($row > $start_index && $row <= $end_index) {
            foreach ($title as $col => $val) {
                $cell_val = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                $strs[$val] = $cell_val;
            }
            $set = true;
            if ($where) {
                foreach ($where as $k => $v) {
                    if (is_array($v)) {
                        switch ($v[0]) {
                            case 'ne':
                                if ($strs[$k] == $v[1]) {
                                    $set = false;
                                }
                                break;
                            case 'eq':
                                if ($strs[$k] != $v[1]) {
                                    $set = false;
                                }
                                break;
                        }
                        if ($set == false) break;
                    } else {
                        if ($strs[$k] != $v) {
                            $set = false;
                            break;
                        }
                    }
                }
            }
            if ($set) {
                $list[] = $strs;
            }

        } else {
            break;
        }
    }
    return array('title' => $title, 'list' => $list, 'err' => 0);
}


function parseExcelE($file, $where = array(), $limit = array(0, 1000))
{
    $title = array();
    $import_file_type = array(
        'xlsx' => 'Excel2007',
        'xls' => 'Excel5',
    );
    error_reporting(E_ALL); //open error
    set_time_limit(0); // script time out
    include_once(dirname(realpath(APP_PATH)) . "/vendor/PHPExcel/PHPExcel/IOFactory.php");
    $pathinfo = pathinfo($file);
    if (!isset($import_file_type[$pathinfo['extension']])) {
    } else {
        $inputFileType = $import_file_type[$pathinfo['extension']];
    }

    $inputFileName = $file;
    try {
        $objReader = PHPExcel_IOFactory::createReader($inputFileType);//set format
        $objPHPExcel = $objReader->load($inputFileName);//loading file
        $objWorksheet = $objPHPExcel->getSheet(0);
        //$objWorksheet = $objPHPExcel->getActiveSheet();//get count rows
        $highestRow = $objWorksheet->getHighestRow();//get count rows
        $highestColumn = $objWorksheet->getHighestColumn();
        $highestColumnIndex = PHPExcel_Cell::columnIndexFromString($highestColumn);//all count cols
    } catch (Exception $e) {
        print_r($e->getMessage());
        return array('err' => 1);
    }

    $start_index = $limit[0] + 1;
    $end_index = $limit[1] + $start_index;
    $headtitle = array();
    $list = array();


    //获取excel文件中的所有图片start
    $sheet = $objWorksheet;
    $imageFilePath = '/static/images/' . date("Y-m-d") . "/";

    if (!file_exists(ROOT_PATH . '/public' . $imageFilePath)) {
        mkdir(ROOT_PATH . '/public' . $imageFilePath, 0777, true);
    }
    $fileImageFj = array();
    foreach ($sheet->getDrawingCollection() as $img) {
        list($startColumn, $startRow) = PHPExcel_Cell::coordinateFromString($img->getCoordinates());//获取图片所在行和列
        $imageFileName = $img->getCoordinates() . mt_rand(1, 1000000000);
        switch ($img->getMimeType()) {
            case 'image/jpg':
                $imageFileName .= '.jpg';
                $file = $imageFilePath . $imageFileName;
                imagejpeg($img->getImageResource(), ROOT_PATH . '/public' . $file);
                break;
            case 'image/gif':
                $imageFileName .= '.gif';
                $file = $imageFilePath . $imageFileName;
                imagegif($img->getImageResource(), ROOT_PATH . '/public' . $file);
                break;
            case 'image/png':
                $imageFileName .= '.png';
                $file = $imageFilePath . $imageFileName;
                imagepng($img->getImageResource(), ROOT_PATH . '/public' . $file);
                break;
        }
        $startColumn = ABC2decimal($startColumn);//由于图片所在位置的列号为字母，转化为数字
        $fileImageFj[$startRow - 1][$startColumn] = $imageFilePath . $imageFileName;//把图片插入到数组中

    }
    //获取excel文件中的所有图片end

    //print_r($fileImageFj);

    $imageColeIdx = -1;//有图片的列是那一列
    for ($row = 1; $row <= $highestRow; $row++) {
        $strs = array();
        if ($row == 1) {
            for ($col = 0; $col < $highestColumnIndex; $col++) {
                $cell_val = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                $cell_val = trim($cell_val);
                if ($cell_val == '附件') {
                    $imageColeIdx = 2;
                }
                if ($row == 1) {
                    if (!$cell_val) {
                        break;
                    }
                }
                $strs[$col] = $cell_val;
            }
            $title = $strs;
        } elseif ($row > $start_index && $row <= $end_index) {
            foreach ($title as $col => $val) {

                $cell_val = $objWorksheet->getCellByColumnAndRow($col, $row)->getValue();
                $cell_val = trim($cell_val);
                if ($col == $imageColeIdx) {
                    if (!empty($fileImageFj[$row - 1][$col])) {
                        $cell_val = $fileImageFj[$row - 1][$col];
                    }
                }
                $strs[$val] = $cell_val;
            }
            $set = true;
            if ($where) {
                foreach ($where as $k => $v) {
                    if (is_array($v)) {
                        switch ($v[0]) {
                            case 'ne':
                                if ($strs[$k] == $v[1]) {
                                    $set = false;
                                }
                                break;
                            case 'eq':
                                if ($strs[$k] != $v[1]) {
                                    $set = false;
                                }
                                break;
                        }
                        if ($set == false) break;
                    } else {
                        if ($strs[$k] != $v) {
                            $set = false;
                            break;
                        }
                    }
                }
            }
            if ($set) {
                $list[] = $strs;
            }

        } else {
            break;
        }
    }
    return array('title' => $title, 'list' => $list, 'err' => 0);
}

function ABC2decimal($abc)
{
    $ten = 0;
    $len = strlen($abc);
    for ($i = 1; $i <= $len; $i++) {
        $char = substr($abc, 0 - $i, 1);//反向获取单个字符

        $int = ord($char);
        $ten += ($int - 65) * pow(26, $i - 1);
    }
    return $ten;
}

function endphpexcel($title, $objPHPExcel, $list)
{
    foreach ($title as $v) {
        $objPHPExcel->getActiveSheet()->setCellValue($v['cell'] . '1', $v['title']);
    }
    $i = 2;
    foreach ($list as $res) {
        foreach ($title as $field => $val) {
            $re = $objPHPExcel->getActiveSheet()->setCellValue($val['cell'] . $i, $res[$field]);
        }
        $i++;
    }
    $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");;
    header('Content-Disposition:attachment;filename="template.xls"');
    header("Content-Transfer-Encoding:binary");
    $objWriter->save('php://output');
    exit();
}

function apiReturnData($data)
{
    $json = json_encode($data, true);
    echo $json;
    exit;
}

function ExportExcelFiles($title, $data, $filename = "", $param = array())
{

    require_once(ROOT_PATH . "/vendor/ExportExcelTool.class.php");
    $Tools = new ExportExcelTool($title, $data, $filename, $param);

    $Tools->generateExcel();

}

/**
 * 生成insert插入语句
 * @param $table 表明
 * @param $data  数据
 * @return string sql
 */
function generaSql($table, $data)
{
    $strv = "";
    $strk = "";
    $k1 = array();
    $v1 = array();
    foreach ($data as $k => $v) {
        $k1[] = '`' . $k . '`';  //将字段作为一个数组；
        $v1[] = '"' . $v . '"';  //将插入的值作为一个数组；
    }
    $strv .= implode(',', $v1);
    $strk .= implode(",", $k1);
    $sql = "insert into " . $table . " ($strk) values ($strv)";
    return $sql;
}


/**
 * 导出excel函数
 * @param array $data 来源数据 数组
 * @param array $title Excel头标题 数组
 * @param string $file_name Excel文件名
 * @param string $worksheet_name Excel工作表名
 *
 * @throws Exception
 */
function createExcel($data, $title, $file_name = 'Excel', $worksheet_name = 'work')
{

    include_once(ROOT_PATH . "/vendor/PHPExcel/PHPExcel.php");
    error_reporting(E_ALL);
    date_default_timezone_set('Europe/London');
    $objPHPExcel = new PHPExcel();

    /*以下是一些设置 ，什么作者  标题啊之类的*/
    /*$objPHPExcel->getProperties()->setCreator("转弯的阳光")
        ->setLastModifiedBy("转弯的阳光")
        ->setTitle("数据EXCEL导出")
        ->setSubject("数据EXCEL导出")
        ->setDescription("备份数据")
        ->setKeywords("excel")
        ->setCategory("result file");*/
    /*以下就是对处理Excel里的数据， 横着取数据，主要是这一步，其他基本都不要改*/
    $cellName = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', "AA", "AB", "AC", "AD", "AE", "AF", "AG", "AH", "AI", "AJ", "AK", "AL", "AM", "AN", "AO", "AP", "AQ", "AR", "AS", "AT", "AU", "AV", "AW", "AX", "AY", "AZ"];
    // 设置excel标题
    $index = 0;
    foreach ($title as $k => $v) {
        $objPHPExcel->getActiveSheet()->setCellValue($cellName[$index] . "1", $v);
        $index++;
    }
    // 填充excel数据 与标题一一对应
    foreach ($data as $k => $v) {
        $num = $k + 2;
        // 重置列索引起始位
        $i = 0;
        foreach ($title as $key => $value) {
            $objPHPExcel->setActiveSheetIndex(0)//Excel的第A列，uid是你查出数组的键值，下面以此类推
            ->setCellValue($cellName[$i] . $num, $v[$key]);
            $i++;
        }
    }
    $objPHPExcel->getActiveSheet()->setTitle($worksheet_name);
    $objPHPExcel->setActiveSheetIndex(0);
    $objWriter = new \PHPExcel_Writer_Excel5($objPHPExcel);
    header("Pragma: public");
    header("Expires: 0");
    header("Cache-Control:must-revalidate, post-check=0, pre-check=0");
    header("Content-Type:application/force-download");
    header("Content-Type:application/vnd.ms-execl");
    header("Content-Type:application/octet-stream");
    header("Content-Type:application/download");;
    header('Content-Disposition:attachment;filename="' . $file_name . '.xls"');
    header("Content-Transfer-Encoding:binary");
    $objWriter->save('php://output');
    exit();
}

/**
 * 创建一个读取excel数据
 * @param string $path excel文件绝对路径
 * @param string $ext excel文件后缀
 *
 * @return mixed        返回数组格式的Excel文件数据
 * @throws Exception
 */
function readExcel($path, $ext = 'xls')
{
    //引用PHPexcel 类
    include_once(ROOT_PATH . "/vendor/PHPExcel/PHPExcel.php");
    include_once(ROOT_PATH . "/vendor/PHPExcel/PHPExcel/IOFactory.php");//静态类
    if ($ext == 'xls') {
        $type = 'Excel5';//设置为Excel5代表支持2003或以下版本，Excel2007代表2007版
    } else {
        $type = 'Excel2007';//设置为Excel5代表支持2003或以下版本，Excel2007代表2007版
    }
    $xlsReader = PHPExcel_IOFactory::createReader($type);
    $xlsReader->setReadDataOnly(true);
    $xlsReader->setLoadSheetsOnly(true);
    $Sheets = $xlsReader->load($path);
    //开始读取上传到服务器中的Excel文件，返回一个二维数组
    $dataArray = $Sheets->getSheet(0)->toArray();
    return $dataArray;
}

/**
 * 下载模板文件
 * @param string $template_filename 模板文件名
 */
function download_template_file($template_filename)
{
    header("Content-type:text/html;charset=utf-8");
    //用以解决中文不能显示出来的问题
    $file_sub_path = ROOT_PATH . "/public/upload/templates/" . $template_filename;
    //首先要判断给定的文件存在与否
    if (!file_exists($file_sub_path)) {
        echo "没有该文件文件";
        return;
    }
    $fp = fopen($file_sub_path, "r");
    $file_size = filesize($file_sub_path);
    //下载文件需要用到的头
    Header("Content-type: application/octet-stream");
    Header("Accept-Ranges: bytes");
    Header("Accept-Length:" . $file_size);
    Header("Content-Disposition: attachment; filename=" . $template_filename);
    $buffer = 1024;
    $file_count = 0;
    //向浏览器返回数据
    while (!feof($fp) && $file_count < $file_size) {
        $file_con = fread($fp, $buffer);
        $file_count += $buffer;
        echo $file_con;
    }
    fclose($fp);
}

/**
 * @param $fields 字段名称 array()
 * @param $data 导出数据 array()
 * @param $filename 导出文件名称  1.pdf
 * @param string $title 导出数据标题
 */
function exportPDFE($fields, $data, $filename, $title = "")
{
    $l = Array();
    require_once(dirname(realpath(APP_PATH)) . "/vendor/Pdf/base/tablePDF.php");
    $pdf = new TablePDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING);
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    if (@file_exists(dirname(realpath(APP_PATH)) . "/vendor/Pdf/base/lang/eng.php")) {

        require_once(dirname(realpath(APP_PATH)) . "/vendor/Pdf/base/lang/eng.php");
        $pdf->setLanguageArray($l);
    }
    $pdf->AddPage();
    $header = array();
    $fieldKey = array();
    foreach ($fields as $key => $val) {
        $header[] = $val;
        $fieldKey[] = $key;
    }
    $edata = array();
    $ik = 0;
    $tlen = count($fieldKey);
    foreach ($data as $key => $val) {
        for ($i = 0; $i < $tlen; $i++) {
            $edata[$ik][] = $val[$fieldKey[$i]];
        }
        $ik++;
    }
    $pdf->ColoredTable($header, $edata);
    $pdf->Output($filename, 'D');

}

/**
 * @param array $fields 字段名称 array()
 * @param array $data 导出数据 array()
 * @param string $filename 导出文件名称  1.txt
 * @param string $title 导出数据标题
 */
function exportTxt($fields, $data, $filename, $title = "")
{
    Header("Content-type:   application/octet-stream ");
    Header("Accept-Ranges:   bytes ");
    header("Content-Disposition:   attachment;   filename=" . $filename . ".txt ");
    header("Expires:   0 ");
    header("Cache-Control:   must-revalidate,   post-check=0,   pre-check=0 ");
    header("Pragma:   public ");
    $ctitle = $tag = '';
    foreach ($fields as $key => $value) {
        $ctitle .= $tag . $value;
        $tag = "|";
    }
    $content = "";
    foreach ($data as $r) {
        $tag1 = "";
        foreach ($fields as $k => $v) {
            $content .= $tag1 . $r[$k];
            $tag1 = "|";
        }
        $content .= "\r\n";
    }
    echo $title . "\r\n";
    echo $ctitle . "\r\n";
    echo $content;
}

function exportPDF($fields, $data, $filename, $title = "", $widthArr = array())
{
    $l = Array();
    require_once(dirname(realpath(APP_PATH)) . "/vendor/Pdf/base/tcpdf_include.php");
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->SetHeaderData("", 0, $title, "");
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    if (@file_exists(dirname(realpath(APP_PATH)) . "/vendor/Pdf/base/lang/eng.php")) {
        require_once(dirname(realpath(APP_PATH)) . "/vendor/Pdf/base/lang/eng.php");
        $pdf->setLanguageArray($l);
    }
    $pdf->AddPage();
    $html = '<style>th{color:white;background-color:#00a3d8;text-align: center;line-height:30px;height:40px;border:1px solid #cfcfcf;}td{border:1px solid #cfcfcf;line-height:30px;text-align: center}';
    foreach ($widthArr as $k => $v) {
        $html .= '.c' . $k . '{width:' . $v . 'px}';
    }
    $html .= '</style>';
    $html .= '<table>';
    $header = array();
    $fieldKey = array();
    $html .= '<tr>';
    foreach ($fields as $key => $val) {
        $header[] = $val;
        $fieldKey[] = $key;
        if (isset($widthArr[$key])) {
            $html .= "<th class='c" . $key . "'>" . $val . "</th>";
        } else {
            $html .= '<th>' . $val . '</th>';
        }
    }
    $html .= '</tr>';
    $ik = 0;
    $tlen = count($fieldKey);
    foreach ($data as $key => $val) {
        $html .= '<tr>';
        for ($i = 0; $i < $tlen; $i++) {
            $html .= '<td>' . $val[$fieldKey[$i]] . '</td>';
        }
        $ik++;
        $html .= '</tr>';
    }
    $html .= '</table>';
    $pdf->writeHTML($html, true, false, false, false, '');
    $pdf->Output($filename . ".pdf", 'D');
}

/**
 * 系统邮件发送函数
 * @param string $tomail 接收邮件者邮箱
 * @param string $name 接收邮件者名称
 * @param string $subject 邮件主题
 * @param string $body 邮件内容
 * @param string $attachment 附件列表
 * @return boolean
 * @author static7 <static7@qq.com>
 */
function send_mail($tomail, $name, $subject = '', $body = '', $attachment = null)
{
    require_once dirname(realpath(APP_PATH)) . "/vendor/PHPMailer/src/PHPMailer.php";
    require_once dirname(realpath(APP_PATH)) . "/vendor/PHPMailer/src/SMTP.php";
    //实例化PHPMailer对象
    $mail = new \PHPMailer();           //实例化PHPMailer对象
    $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
    $mail->IsSMTP();                    // 设定使用SMTP服务
    $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
    $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
//    $mail->SMTPSecure = 'ssl';          // 使用安全协议
    $mail->Host = "smtp.qq.com"; // SMTP 服务器
//    $mail->Port = 465;                  // SMTP服务器的端口号
    $mail->Username = "381878593@qq.com";    // SMTP服务器用户名
    $mail->Password = "qxbtonsgwrajbihe";     // SMTP服务器密码
    $mail->SetFrom('381878593@qq.com', 'static7');
    $replyEmail = '';                   //留空则为发件人EMAIL
    $replyName = '';                    //回复名称（留空则为发件人名称）
    $mail->AddReplyTo($replyEmail, $replyName);
    $mail->Subject = $subject;
    $mail->MsgHTML($body);
    $mail->AddAddress($tomail, $name);
    if (is_array($attachment)) { // 添加附件
        foreach ($attachment as $file) {
            is_file($file) && $mail->AddAttachment($file);
        }
    }
    return $mail->Send() ? true : $mail->ErrorInfo;
}

/**
 * 获取session中设定的字段
 * @param string $key session键名 (表名)
 * @param $source_fields 原始字段键名
 * @return array         返回目标字段键名
 */
function export_fields($key, $source_fields)
{
    $session_fields = explode(',', session($key));
    $fields = [];
    foreach ($session_fields as $v) {
        if (isset($source_fields[$v])) {
            $fields[$v] = $source_fields[$v];
        }
    }
    return $fields;
}

/**
 * 单个图片上传
 * @param string $imagename 表单中图片文件元素name值
 * @return mixed
 */
function uploadImage($imagename)
{
    $return = ['msg' => '', 'err' => 100];
    // 获取表单上传文件 例如上传了001.jpg
    $file = request()->file($imagename);
    // 移动到框架应用根目录/public/uploads/ 目录下
    if ($file) {
        $movePath = ROOT_PATH . 'public' . DS . 'upload' . DS . 'images';
        $info = $file->validate(['size' => 156780000, 'ext' => 'jpg,png,gif,jpeg'])->move($movePath);

        if ($info) {

            $filename = $info->getSaveName();
            $tempFileNameString = explode(".", $filename);
            $fileCurrPath = $movePath . "/" . $filename;
            $image = \think\Image::open($fileCurrPath);
            $savethumb1 = $movePath . "/" . $tempFileNameString[0] . "_1." . $tempFileNameString[1];
            $savethumb2 = $movePath . "/" . $tempFileNameString[0] . "_2." . $tempFileNameString[1];
            $savethumb3 = $movePath . "/" . $tempFileNameString[0] . "_3." . $tempFileNameString[1];
            $thumbConfig = config('UPLOAD_IMG');
            $image->thumb($thumbConfig['thumb1']['width'], $thumbConfig['thumb1']['height'])->save($savethumb1);
            $image->thumb($thumbConfig['thumb2']['width'], $thumbConfig['thumb2']['height'])->save($savethumb2);
            $image->thumb($thumbConfig['thumb3']['width'], $thumbConfig['thumb3']['height'])->save($savethumb3);
            $return = [
                'msg' => '上传成功',
                'err' => 0,
                'url' => "/upload/images/" . $filename,
                'thumb1' => "/upload/images/" . $tempFileNameString[0] . "_1." . $tempFileNameString[1],
                'thumb2' => "/upload/images/" . $tempFileNameString[0] . "_2." . $tempFileNameString[1],
                'thumb3' => "/upload/images/" . $tempFileNameString[0] . "_3." . $tempFileNameString[1],
            ];
        } else {
            // 上传失败获取错误信息
            $msg = $file->getError();
            $return = ['msg' => $msg, 'err' => 1];
        }
    }
    return $return;
}

/**
 * 多个图片上传
 * @param string $imagename 表单中图片文件元素name值
 * @return string
 */
function uploadMoreImage($imagename)
{
    // 获取表单上传文件
    $files = request()->file($imagename);
    $return = '';
    foreach ($files as $file) {
        // 移动到框架应用根目录/public/uploads/ 目录下
        $info = $file->move(ROOT_PATH . 'public' . DS . 'upload' . DS . 'images');
        if ($info) {
            // 成功上传后 获取上传信息

        } else {
            // 上传失败获取错误信息
            $return .= $file->getError();
        }
    }
    return $return;
}

/**验证传入的数据是否是整数
 * @param $num
 * @param bool $flag
 * @return bool
 */
function inputvalidateNum($num, $flag = false)
{
    if ($flag) {
        if ($num == '0') {
            return true;
        }
    }
    if (empty($num)) {
        return false;
    }
    if (!is_numeric($num)) {
        return false;
    }
    return true;
}


function uploadPicture($file, $path = '')
{
    $return = array();
    $movepath = ROOT_PATH . 'public' . DS . $path;
    if ($file) {
        $info = $file->validate(['ext' => 'jpg,png,gif,zip,rar,jpeg,apk,txt,doc,docx,xls,xlsx'])->move($movepath);
        if ($info) {
            $return['err'] = 0;
            $return['msg'] = '上传成功';
            $return['file'] = array(
                'ext' => $info->getExtension(),
                'path' => $info->getSaveName(),
                'filename' => $info->getFilename(),
                'url' => DS . $path . DS . $info->getSaveName(),
            );
        } else {
            $return['err'] = 1;
            $return['msg'] = '上传失败';
        }
    } else {
        $return['err'] = 1;
        $return['msg'] = '上传失败';
    }
    return $return;
}

function generaUploadPath($uid, $type = "files")
{
    $currDate = getCurrDate();
    $path = 'uploads' . DS . $uid . DS . $type;
    return $path;
}

function uploadFiles($file, $path = '')
{
    $fileInfo = $file->getInfo();
    if (!is_dir(ROOT_PATH . 'public' . DS . $path)) {
        //  echo ROOT_PATH . 'public' .DS. $path;
        mkdir(ROOT_PATH . 'public' . DS . $path, 0777);
        chmod(ROOT_PATH . 'public' . DS . $path, 0755);
    }
    $path = DS . $path . DS . $fileInfo['name'];
    $tempSavePath = $path;
    $path = iconv("UTF-8", "gb2312", $path);

    $return = array();
    $movepath = ROOT_PATH . 'public' . $path;
    $tempMovePath = ROOT_PATH . 'public' . $tempSavePath;
    if ($fileInfo['tmp_name']) {
        $flag = move_uploaded_file($fileInfo['tmp_name'], $movepath);
        if ($flag) {
            $path = iconv("gb2312", "UTF-8", $path);
            $return['err'] = 0;
            $return['msg'] = '上传成功';
            $return['file'] = array(
                'ext' => $fileInfo['type'],
                'path' => $tempMovePath,
                'filename' => $fileInfo['name'],
                'url' => $tempSavePath,
            );
        } else {
            $return['err'] = 1;
            $return['msg'] = '上传失败';
            $return['data'] = $fileInfo;
        }

    } else {
        $return['err'] = 1;
        $return['msg'] = '上传失败';
        $return['data'] = $fileInfo;
    }
    return $return;
}


function uploadFinger($file, $path = '', $filename = true, $rule = 'date')
{
    $return = array();
    $movepath = ROOT_PATH . 'public' . DS . $path;
    if ($file) {
        $file->rule($rule);
        $info = $file->validate(['ext' => 'jpg,png,gif,zip,rar,jpeg,apk,txt,doc,docx,xls,xlsx'])->move($movepath, $filename);
        if ($info) {
            $return['err'] = 0;
            $return['msg'] = '指纹文件上传成功';
            $return['file'] = array(
                'ext' => $info->getExtension(),
                'path' => $info->getSaveName(),
                'filename' => $info->getFilename(),
                'url' => DS . $path . DS . $info->getSaveName(),
            );
        } else {
            $return['err'] = 1;
            $return['msg'] = '指纹文件上传失败' . $file->getError();
        }
    } else {
        $return['err'] = 1;
        $return['msg'] = '指纹文件上传失败';
    }
    return $return;
}

function getCurrDate()
{
    return array(
        'year' => date('Y'),
        'month' => date('m'),
        'day' => date('d'),
        'hour' => date('H'),
        'minute' => date('i'),
        'second' => date('s'),
        'time' => time(),
        'date' => date('Y-m-d H:i:s'),
        'date1' => date('Y-m-d'),
        'simple' => date('Y-m-d'),
    );
}


function generateZipPackage($path, $zipName)
{

    try {
        $fileNameArr = selfScandir(ROOT_PATH . 'public' . DS . $path);
        $ZipFilenName = ROOT_PATH . 'public' . DS . 'upload' . DS . 'syszip' . DS . $zipName;
        $zip = new ZipArchive (); // 使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
        if ($zip->open($ZipFilenName, ZIPARCHIVE::CREATE) !== TRUE) {
            return array(
                'err' => 1,
                'mag' => '打包失败'
            );
        }
        $zip->addFile(ROOT_PATH . 'public/readme.txt', 'readme.txt'); // 第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        foreach ($fileNameArr as $val) {
            if (DS == '/') {
                $temp = explode("/", $val);
            } else {
                $temp = explode("\\", $val);
            }
            $tlen = count($temp);
            $zip->addFile($val, $temp[$tlen - 1]); // 第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
        $zip->close(); // 关闭
        return array(
            'err' => 0,
            'msg' => '打包成功',
            'zip' => array(
                'path' => $ZipFilenName,
                'url' => DS . 'upload' . DS . 'syszip' . DS . $zipName
            )
        );
    } catch (Exception $e) {
        return array(
            'err' => 1,
            'mag' => '打包失败'
        );
    }
}


function generateZipPackageE($zipName, $lists = array())
{
    try {
        $ZipFilenName = ROOT_PATH . 'public' . DS . 'upload' . DS . 'syszip' . DS . $zipName;
        $zip = new ZipArchive (); // 使用本类，linux需开启zlib，windows需取消php_zip.dll前的注释
        if ($zip->open($ZipFilenName, ZIPARCHIVE::CREATE) !== TRUE) {
            return array(
                'err' => 1,
                'mag' => '打包失败'
            );
        }

        $zip->addFile(ROOT_PATH . 'public/readme.txt', 'readme.txt'); // 第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下


        foreach ($lists as $val) {
            if (DS == '/') {
                $temp = explode("/", $val);
            } else {
                $temp = explode("\\", $val);
            }
            $tlen = count($temp);
            $zip->addFile($val, $temp[$tlen - 1]); // 第二个参数是放在压缩包中的文件名称，如果文件可能会有重复，就需要注意一下
        }
        $zip->close(); // 关闭

        return array(
            'err' => 0,
            'msg' => '打包成功',
            'zip' => array(
                'path' => $ZipFilenName,
                'url' => DS . 'upload' . DS . 'syszip' . DS . $zipName
            )
        );
    } catch (Exception $e) {
        return array(
            'err' => 1,
            'mag' => '打包失败'
        );
    }
}

function selfScandir($dir)
{
    $files = array();
    if (is_dir($dir)) {
        if ($handle = opendir($dir)) {
            while (($file = readdir($handle)) !== false) {
                if ($file != '.' && $file != "..") {
                    if (is_dir($dir . "/" . $file)) {
//                        $files[$file]=selfScandir($dir."/".$file);
                        $temp = selfScandir($dir . "/" . $file);
                        $files = array_merge($files, $temp);

                    } else {
                        $files[] = $dir . "/" . $file;
                    }
                }
            }
            closedir($handle);
        }
    }
    return $files;
}

/**
 * 后台教师账号的密码加密还是
 * @param $pwd
 * @return mixed
 */
function teacherPWD($pwd)
{
    return MD5(config("auth_key.teacher_login_key") . $pwd);
}

/**生成教师登陆的auth信息
 * @param $array
 * @param string $algorithm
 * @return string
 */
function teacherAuth($array, $algorithm = 'ecb')
{
    if (empty($array)) {
        return '';
    }
    $data = json_encode($array, true);
    $key = config("auth_key.teacher_auth_key");
    return encrypt3des($data, $key);
}

function parseTeacherAuth($auth)
{

    if (!$auth) {
        return array('err' => 1, 'msg' => 'auth信息为空');
    }
    $key = config("auth_key.teacher_auth_key");
    $temp = decrypt3des($auth, $key);
    $data = json_decode($temp, true);
    if (!empty($data)) {
        return array('err' => 0, 'msg' => '解析成功', 'data' => $data);
    } else {
        return array('err' => 1, 'msg' => '解析失败');
    }
}

function updateTeacherAuth($auth)
{
    if (empty($auth)) {
        return '';
    }
    $data = parseTeacherAuth($auth);

    if ($data['err'] != 0) {
        return '';
    }
    $data = $data['data'];
    $data['last_access'] = time();
    $key = config("auth_key.teacher_auth_key");
    $data = json_encode($data, true);
    return encrypt3des($data, $key);
}


/**生成教师登陆的auth信息
 * @param $array
 * @param string $algorithm
 * @return string
 */
function guardianAuth($array, $algorithm = 'ecb')
{
    if (empty($array)) {
        return '';
    }
    $data = json_encode($array, true);
    $key = config("auth_key.guardian_auth_key");
    return encrypt3des($data, $key);
}

function parseGuardianAuth($auth)
{

    if (!$auth) {
        return array('err' => 1, 'msg' => 'auth信息为空');
    }
    $key = config("auth_key.guardian_auth_key");
    $temp = decrypt3des($auth, $key);
    $data = json_decode($temp, true);
    if (!empty($data)) {
        return array('err' => 0, 'msg' => '解析成功', 'data' => $data);
    } else {
        return array('err' => 1, 'msg' => '解析失败');
    }
}

function updateGuardianAuth($auth)
{
    if (empty($auth)) {
        return '';
    }
    $data = parseGuardianAuth($auth);

    if ($data['err'] != 0) {
        return '';
    }
    $data = $data['data'];
    $data['last_access'] = time();
    $key = config("auth_key.guardian_auth_key");
    $data = json_encode($data, true);
    return encrypt3des($data, $key);
}


/** 3des加密
 * @param $data
 * @param string $algorithm
 * @return mixed
 */
function encrypt3des($data, $key, $iv = '', $algorithm = 'ecb')
{
    $des = new think\Crypt3Des($key, $iv);
    if ($algorithm == 'ecb') {
        return $des->encrypt($data);
    } else {
        return $des->do_encrypt_x($data);
    }
}


function decrypt3des($data, $key, $iv = '', $algorithm = 'ecb')
{
    if ($data === '') {
        return $data;
    }
    $des = new \think\Crypt3Des($key, $iv);
    if ($algorithm == 'ecb') {
        return $des->decrypt($data);
    } else {
        return $des->do_decrypt_x($data);
    }
}


function taskStatus($stat)
{
    $str = '';
    if ($stat == 0) {
        $str = '<font style="color:red">提交</font>';
    } else if ($stat == 1) {
        $str = '<font style="color:green">执行</font>';
    } else if ($stat == 2) {
        $str = '<font >完结</font>';
    }
    return $str;
}


function make_dir($dir)
{
    if (!file_exists($dir)) {
        @make_dir(dirname($dir), 0775);
        @mkdir($dir, 0775);
    }
}


/**
 * 后台教师账号的密码加密还是
 * @param $pwd
 * @return mixed
 */
function guardionPWD($pwd)
{
    return MD5(config("auth_key.guardion_login_key") . $pwd);
}

/**生成教师登陆的auth信息
 * @param $array
 * @param string $algorithm
 * @return string
 */
function guardionAuth($array, $algorithm = 'ecb')
{
    if (empty($array)) {
        return '';
    }
    $data = json_encode($array, true);
    $key = config("auth_key.guardion_auth_key");
    return encrypt3des($data, $key);
}


function updateGuardionAuth($auth)
{
    if (empty($auth)) {
        return '';
    }
    $data = parseTeacherAuth($auth);

    if ($data['err'] != 0) {
        return '';
    }
    $data = $data['data'];
    $data['last_access'] = time();
    $key = config("auth_key.guardion_auth_key");
    $data = json_encode($data, true);
    return encrypt3des($data, $key);
}

function numberToWeek($num)
{
    $string = "";
    switch ($num) {
        case 0:
            $string = '星期天';
            break;
        case 1:
            $string = '星期一';
            break;
        case 2:
            $string = '星期二';
            break;
        case 3:
            $string = '星期三';
            break;
        case 4:
            $string = '星期四';
            break;
        case 5:
            $string = '星期五';
            break;
        case 6:
            $string = '星期六';
            break;
        case 7:
            $string = '星期天';
            break;
    }
    return $string;
}

function getWeekData($date)
{
    $rdata = array();
    $time = strtotime($date);
    $da = date("w", $time);
    if ($da == 0) {
        $da = 7;
    }
    for ($i = 1; $i <= $da; $i++) {
        $tempString = $da - $i;
        $tdate = strtotime("-" . $tempString . "days", $time);
        $rdata[] = array(
            'year' => date("Y", $tdate),
            'month' => date("m", $tdate),
            'day' => date("d", $tdate),
            'date' => date("Y-m-d", $tdate),
            'name' => numberToWeek($i),
        );
    }

    for ($i = $da + 1; $i <= 7; $i++) {
        $tempString = $i - $da;
        $tdate = strtotime("+" . $tempString . "days", $time);
        $rdata[] = array(
            'year' => date("Y", $tdate),
            'month' => date("m", $tdate),
            'day' => date("d", $tdate),
            'date' => date("Y-m-d", $tdate),
            'name' => numberToWeek($i),
        );
    }
    return $rdata;
}

function changeInt($num)
{
    return (int)$num;
}

/**
 * 获取微信公众号的openid等信息
 * @return multitype:number string |multitype:number string multitype:unknown mixed
 */
function getOpenid($school_id = 0)
{
    define("APPID", config('WEIXIN.APPID'));
    define("APPSECRET", config('WEIXIN.APPSECRET'));
    define("TOKEN", config('WEIXIN.TOKEN'));
    include_once(dirname(realpath(APP_PATH)) . "/vendor/wx/webChat.class.php");
    $wechatObj = new \webChat(APPID, APPSECRET, TOKEN);
    $code = trim($_REQUEST['code']);//code码
    $state = trim($_REQUEST['state']);//发起授权是随机数
    if (empty($code)) {
        return array(
            'err' => 1,
            'msg' => '授权失败'
        );
    }
    //通过code码获取 网页授权access_token
    $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . APPID . "&secret=" . APPSECRET . "&code={$code}&grant_type=authorization_code";
    $rdata = $wechatObj->postData($url, "", true, 'GET');
    $access_arr = json_decode($rdata, true);
    if (empty($access_arr['access_token'])) {
        return array(
            'err' => 2,
            'msg' => 'access_token获取失败'
        );
    }
    $access_token = $access_arr['access_token'];
    $openid = $access_arr['openid'];
    $scope = $access_arr['scope'];
    return array(
        'err' => 0,
        'msg' => '成功',
        'data' => array(
            'access_token' => $access_token,
            'scope' => $scope,
            'openid' => $openid,
        )
    );
}

/**
 * 根据秒 计算多年月日
 * @param unknown $time
 * @return string|boolean
 */
function changeSecondToDate($time)
{
    if (is_numeric($time)) {
        $value = array(
            "years" => 0, "days" => 0, "hours" => 0,
            "minutes" => 0, "seconds" => 0,
        );
        if ($time >= 3600 * 24 * 365) {
            $value["years"] = floor($time / (3600 * 24 * 365));
            $time = $time % (3600 * 24 * 365);
        }
        if ($time >= 3600 * 24) {
            $value["days"] = floor($time / (3600 * 24));
            $time = $time % (3600 * 24);
        }
        $t = $value["years"] . "岁" . $value["days"] . "天";
        return $t;

    } else {
        return '0岁0天';
    }
}

/**
 * 获取任意一个月份的总天数
 * @param $date
 * @return string
 */
function getMonthDayForYear($date)
{
    $tempSecond = strtotime($date);
    $year = date("Y", $tempSecond);
    $month = date("n", $tempSecond);//m:01-12,n:1-12
    if (in_array($month, array(1, 3, 5, 7, 8, 10, 12))) {
        // $text = $year.'年的'.$month.'月有31天';
        $text = '31';
    } elseif ($month == 2) {
        if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0))    //判断是否是闰年
        {
            // $text = $year.'年的'.$month.'月有29天';
            $text = '29';
        } else {
            // $text = $year.'年的'.$month.'月有28天';
            $text = '28';
        }
    } else {
        // $text = $year.'年的'.$month.'月有30天';
        $text = '30';
    }
    return $text;
}

function zhoujiForMothFirstDays($month)
{
    $zhouji = date("w", strtotime($month . "-01"));
    return $zhouji;
}

function zhouji()
{
    $zhouji = date("w", strtotime(date("Y-m-01")));
    return $zhouji;
}

function getCurDayWeek()
{
    $zhouji = date("w", strtotime(date("Y-m-d")));
    if ($zhouji == 0) {
        $zhouji = 7;
    }
    return $zhouji;
}

/**
 * 获取本月天数
 * @param $date
 * @return int
 */
function getCurMonthDay($date)
{
//     cal_days_in_month(CAL_GREGORIAN, $month, $year);
    $totleNum = 0;
    $tempSecond = strtotime($date);
    $year = date("Y", $tempSecond);
    $month = date("n", $tempSecond);
    if (in_array($month, array(1, 3, 5, 7, 8, 10, 12))) {
        $totleNum = 31;
    } elseif ($month == 2) {
        if ($year % 400 == 0 || ($year % 4 == 0 && $year % 100 !== 0))        //判断是否是闰年
        {
            $totleNum = 29;
        } else {
            $totleNum = 28;
        }
    } else {

        $totleNum = 30;
    }
    return $totleNum;
}

function getCurrWeekDays()
{
    $return = array();
    $zhouji = getCurDayWeek();//获取今天是周几
    $myTmp = date("Y-m");
    $monthNum = getCurMonthDay($myTmp);//获取本月是多少天
    //之前
    $start = $zhouji - 1;
    if ($start > 0) {
        for ($i = $start; $i > 0; $i--) {
            $return[] = array(
                'date' => date("Y-m-d", strtotime("-" . $i . "days")),
                'f' => 0,
                'w' => numberToWeek($zhouji - $i)
            );
        }
    }

    $return[] = array(
        'date' => date("Y-m-d"),
        'f' => 1,
        'w' => numberToWeek($zhouji)
    );

    $end = 7 - $zhouji;
    if ($end > 0) {

        for ($i = $zhouji + 1; $i <= 7; $i++) {
            $wei = $i - $zhouji;
            $return[] = array(
                'date' => date("Y-m-d", strtotime("+" . $wei . "days")),
                'f' => 0,
                'w' => numberToWeek($i)
            );
        }
    }
    return $return;

}

function getWeekDays($date)
{
    $curr = date("Y-m-d");
    $tdata = strtotime($date);
    $alt = zhoujiE($date);
    $return = array();
    if ($alt == "星期一") {
        for ($i = 7; $i >= 1; $i--) {
            $arrt = array(
                'date' => date("Y-m-d", strtotime("-" . $i . "days", $tdata)),
                'f' => 0,
                'w' => numberToWeek(7 - $i + 1)
            );
            if ($arrt['date'] == $curr) {
                $arrt['f'] = 1;
            }
            $return[] = $arrt;
        }

    } else {
        for ($i = 1; $i <= 7; $i++) {
            $arrt = array(
                'date' => date("Y-m-d", strtotime("+" . $i . "days", $tdata)),
                'f' => 0,
                'w' => numberToWeek($i)
            );
            if ($arrt['date'] == $curr) {
                $arrt['f'] = 1;
            }
            $return[] = $arrt;
        }
    }
    return $return;

}

function RecordLoginLog($table, $data)
{

    $sql = generaSql("t_" . $table, $data);
    return \think\Db::query($sql);

}

function zhoujiE($date)
{
    $zhouji = date("w", strtotime(date($date)));
    return numberToWeek($zhouji);
}

/**
 * 执行查询sql语句
 * @param unknown $sql
 */
function querySelectSQL($sql)
{
    $result = \think\Db::query($sql);
    return $result;
}

/**
 * 自定义链接mysql数据库
 * @return mysqli
 */
function conn_mysqli()
{
    $config = include(dirname(realpath(APP_PATH)) . "/application/database.php");
    $mysqli = mysqli_connect(
        $config['hostname'],
        $config['username'],
        $config['password'],
        $config['database'],
        $config['hostport']
    );
    if (mysqli_connect_errno()) {
        $msg_error = mysqli_connect_error();
        printf("Connect failed:" . $msg_error);
        exit ();
    }
    mysqli_query($mysqli, "SET NAMES utf8");
    return $mysqli;
}


function qrcodes($cid, $gid, $sid)
{
    include_once(dirname(realpath(APP_PATH)) . "/vendor/phpqrcode/qrlib.php");
    $PNG_TEMP_DIR = dirname(realpath(APP_PATH)) . "/public/static/";
    //html PNG location prefix
    $PNG_WEB_DIR = "/static/";
    $filename = $PNG_TEMP_DIR . 'test.png';
    $qr_size = 9;
    $qr_level = 'M';
    $selectUrl = 'http://www.huaerbaby.com/myteacher/add_student_back.html?x=' . $cid . '&y=' . $gid . '&z=' . $sid;
    $errorCorrectionLevel = $qr_level;
    $matrixPointSize = 4;
    $matrixPointSize = min(max($qr_size, 1), 10);
    $filename = $PNG_TEMP_DIR . 'test' . md5($selectUrl) . '.png';
    \QRcode::png($selectUrl, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
    $turls = 'http://www.huaerbaby.com' . $PNG_WEB_DIR . basename($filename);
    return $turls;
}

function UserPwdE($pwd)
{
    return userPWD($pwd);
}

function userPWD($pwd)
{
    $passwd = MD5(config("auth_key.user_login_key") . $pwd);
    return trim($passwd);
}

function encodeCookie($array, $algorithm = 'ecb')
{
    if (empty($array)) {
        return '';
    }
    $data = json_encode($array, true);
    $key = config("auth_key.cookie_key");
    return encrypt3des($data, $key);
}

function decodeCookie($auth)
{

    if (!$auth) {
        return array('err' => 1, 'msg' => 'auth信息为空');
    }
    $key = config("auth_key.cookie_key");
    $temp = decrypt3des($auth, $key);
    $data = json_decode($temp, true);
    if (!empty($data)) {
        return array('err' => 0, 'msg' => '解析成功', 'data' => $data);
    } else {
        return array('err' => 1, 'msg' => '解析失败');
    }
}

function autoGerCode($pre = "")
{

    $s = date('Ymd') . mt_rand(1000000, 9999999);
    return $pre . $s;

}

function generalCal($date = "2018-09", $currDate = "2018-09-18")
{

    include_once(dirname(realpath(APP_PATH)) . "/vendor/myCal/myCal.php");
    $calendar = new MyCal();
    $temp = explode("-", $date);
    $year = $temp[0];
    $month = $temp[1];
    $list = $calendar->getCalendar($year, $month);
    return $list;
}

/**
 * 判断一个字符串是否和另一个字符串相等，或者一个字符串是否在另一个字符串数组中
 * @param $url
 * @param $curr
 * @return bool
 */
function myComparamTwoString($url, $curr)
{
    $url = strtolower($url);
    $currArray = array();
    if (!is_array($curr)) {
        $currArray[0] = $curr;
    } else {
        $currArray = $curr;
    }
    $flag = false;
    foreach ($currArray as $key => $val) {
        $val = strtolower($val);
        if ($url == $val) {
            $flag = true;
            break;
        }
    }
    return $flag;
}

/**
 * 获取当前访问的路径
 * @return string eg:/admin/classlist/adddata
 */
function getCurrAccessPath()
{
    $CurrUrl = $_SERVER['REQUEST_URI'];
    $tempCurr = explode("?", $CurrUrl);
    $currRequestURI = trim($tempCurr[0]);
    $currRequestURI = strtolower($currRequestURI);
    return $currRequestURI;
}

/**
 * 把性别转换成文字
 * @param $sex
 * @return string
 */
function changeSexToName($sex)
{
    $name = '';
    if ($sex == '0') {
        $name = '女';
    } else if ($sex == '1') {
        $name = '男';
    }
    return $name;
}


function base64EncodeImage($image_file)
{
    $base64_image = '';
    $image_info = getimagesize($image_file);
    $image_data = fread(fopen($image_file, 'r'), filesize($image_file));
    //$base64_image = 'data:' . $image_info['mime'] . ';base64,' . chunk_split(base64_encode($image_data));
    $base64_image = chunk_split(base64_encode($image_data));
    return $base64_image;
}

/**
 * 改变二维数据的毽子作为下标
 * @param unknown $list
 * @param unknown $changekey
 * @return multitype:|multitype:unknown
 */
function changeArrayKey($list, $changekey)
{
    if (empty($list)) {
        return array();
    }
    $tempArray = array();
    foreach ($list as $key => $val) {
        $tempArray[$val[$changekey]] = $val;
    }
    return $tempArray;
}


function ToolDownloadImage($url, $path = 'images/')
{
    $CreatePath = ROOT_PATH . 'public' . $path;

    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    $file = curl_exec($ch);
    curl_close($ch);
    $filename = ToolSaveAsImage($url, $file, $CreatePath);
    return $path . $filename;
}

function ToolSaveAsImage($url, $file, $path)
{
    $filename = pathinfo($url, PATHINFO_BASENAME);
    $filename = time() . $filename;
    $resource = fopen($path . $filename, 'a+');
    fwrite($resource, $file);
    fclose($resource);
    return $filename;
}

/**
 * 获取客户端系统
 * 1 android 2 苹果
 * @return number
 */
function get_client_system()
{
    return 0;
}

/**
 * 微信接口api post
 * @param unknown $url
 * @param unknown $data
 * @param string $https
 * @param string $method
 * @return mixed
 */
function WxApiRequest($url, $data = array(), $https = true, $method = 'POST')
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    if ($https) {
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, true);  // 从证书中检查SSL加密算法是否存在
    }
    if ($method == "POST") {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    $handles = curl_exec($ch);
    curl_close($ch);

    return json_decode($handles, true);
}

/**
 * 根据用户ID获取用户数据
 * @param unknown $id
 * @param string $fields
 */
function getUserInfoForID($id, $fields = '*')
{
    //echo "----".$id."<br>";
    $userInfo = \think\Db::query("select " . $fields . " from t_user where  id='" . $id . "'");
    if (empty($userInfo)) {
        return array();
    }
    return $userInfo[0];
}

/**
 * 根据用户账号获取用户数据
 * @param unknown $id
 * @param string $fields
 */
function getUserInfoForUname($uname, $fields = '*')
{
    //echo "----".$id."<br>";
    $userInfo = \think\Db::query("select " . $fields . " from t_user where  uname='" . $uname . "' order by is_delete asc limit 1 ");
    if (empty($userInfo)) {
        return array();
    }
    return $userInfo[0];
}


/**
 * 根据用户姓名模糊匹配用户列表
 * @param unknown $id
 * @param string $fields
 */
function getUserListsForNickname($nickname, $fields = '*')
{
    //echo "----".$id."<br>";
    $sql = "select " . $fields . " from t_user where  nickname like '%" . $nickname . "%' order by is_delete asc";
    $lists = \think\Db::query($sql);
    if (empty($lists)) {
        return array();
    }
    return $lists;
}

/**
 * 根据微信openid 获取用户信息
 * @param $openid
 * @param string $fields
 * @return array
 */
function getUserInfoForOpenid($openid, $fields = '*')
{
    //echo "----".$id."<br>";
    $userInfo = \think\Db::query("select " . $fields . " from t_user where  wechat_openid='" . $openid . "' order by is_delete asc limit 1");
    if (empty($userInfo)) {
        return array();
    }
    return $userInfo[0];
}


/**
 * 把数组中的 uid  装换成userinfo信息
 * @param unknown $lists
 * @param unknown $key1
 * @param unknown $key2
 * @param fields 获取的字段
 * @return multitype:
 */
function changeUidToUserinfoForLists($lists, $key1 = "", $key2 = "", $fields = "id,uname,nickname,weight,height,head,sex,bday,ctime,money,sleep_option,level,vip")
{
    if (empty($lists)) {
        return array();
    }
    static $allUserinfo = array();//静态变量
    foreach ($lists as $k => $v) {
        if (!empty($key1)) {
            $lists[$k]['UserInfo'] = array();
            if ($v[$key1]) {
                if (!empty($allUserinfo[$v[$key1]])) {
                    $lists[$k]['UserInfo'] = $allUserinfo[$v[$key1]];
                } else {

                    $userinfo = getUserInfoForID($v[$key1], $fields);

                    if (!empty($userinfo)) {
                        $allUserinfo[$v[$key1]] = $userinfo;
                        $lists[$k]['UserInfo'] = $userinfo;
                    }
                }
            }
        }


        if (!empty($key2)) {
            $lists[$k]['UserInfo1'] = array();
            if ($v[$key2]) {
                if (!empty($allUserinfo[$v[$key2]])) {
                    $lists[$k]['UserInfo1'] = $allUserinfo[$v[$key2]];
                } else {
                    $userinfo = getUserInfoForID($v[$key2], $fields);
                    if (!empty($userinfo)) {
                        $allUserinfo[$v[$key2]] = $userinfo;
                        $lists[$k]['UserInfo1'] = $userinfo;
                    }
                }
            }
        }
    }
    return $lists;
}


function changeOpenidToUserinfoForLists($lists, $fields = "id,uname,nickname,head,sex,bday,ctime,money,level,vip")
{
    if (empty($lists)) {
        return array();
    }
    static $allUserinfo = array();//静态变量

    foreach ($lists as $k => $v) {
        $lists[$k]['UserInfo'] = array();
        if ($v['wechat_openid']) {
            if (!empty($allUserinfo[$v['wechat_openid']])) {
                $lists[$k]['UserInfo'] = $allUserinfo[$v['wechat_openid']];
            } else {
                $userinfo = getUserInfoForOpenid($v['wechat_openid'], $fields);
                if (!empty($userinfo)) {
                    $allUserinfo[$v['wechat_openid']] = $userinfo;
                    $lists[$k]['UserInfo'] = $userinfo;
                }
            }
        }
    }

    return $lists;
}

/**
 * 把字符串按照指定字符切割成数据
 * @param $string
 * @param string $split
 * @return array
 */
function explodeStringToArray($string, $split = ",")
{
    if (empty($string)) {
        return array();
    }
    return explode($split, $string);
}


/**
 * 删除磁盘文件
 * @param unknown $file
 */
function removeFileForDirectory($file)
{
    if (!empty($file)) {
        $path = ROOT_PATH . "public" . $file;
        @unlink($path);
    }
}


function changeNumToKeyScore($k)
{
    return 'k' . $k;
}


function isOverTime($date)
{
    $string = "";
    $cur = date("Y-m-d");
    if ($cur > $date) {
        $string = "<font>过期</font>";
    } else {
        $string = "<font>等待</font>";
    }
    return $string;
}


function tuijianStats($stats)
{
    $string = "";

    if ($stats == 0) {
        $string = "<font>普通</font>";
    } else {
        $string = "<font>推荐</font>";
    }
    return $string;
}

function msgStats($stats)
{
    $string = "";
    $cur = date("Y-m-d");
    if ($stats == 0) {
        $string = "<font>等待</font>";
    } else {
        $string = "<font>已推送</font>";
    }
    return $string;
}


function getFilesForIDS($ids = array())
{
    if (empty($ids)) {
        return array();
    }
    $sql = "select * from p_files where id in(" . implode(",", $ids) . ")";
    $lists = \think\Db::query($sql);
    if (!empty($lists)) {
        return $lists;
    }
    return array();
}

/**
 * 给小程序发送订阅模板消息
 * @param $openid
 * @param $templateid
 * @param $messageBody
 * @param $hosp_id
 * @param $client
 * @return array|mixed
 */
function wechatSendSubscribeTemplateMsg($hosp_id, $client, $openid, $templateid, $page, $miniprogram_state, $data)
{

    $Config = config('WEIXIN_APP');
    $Config = $Config[$hosp_id];
    if($client==1) {
        $Config = $Config['userClient'];
    }else if($client==2)
    {
        $Config = $Config['doctorClient'];
    }
    if(!empty($Config['miniprogram_state']))
    {
        $miniprogram_state = $Config['miniprogram_state'];
    }

    $tempToken = wechatGetAccessToken($hosp_id, $client);//获取access_token
    if ($tempToken['err']) {
        return array('err' => 1, 'msg' => "access_token为空");
    }
    $access_token = $tempToken['access_token'];

    $formwork = '{
         "touser": "' . $openid . '",
         "template_id": "' . $templateid . '",
         "page": "' . $page . '",
         "miniprogram_state": "' . $miniprogram_state . '",
          "lang":"zh_CN",
         "data": ' . $data . '
 }';

    // $formwork=$data;
    $url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" . $access_token;
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $formwork);
    $data = curl_exec($ch);
    curl_close($ch);
    $data = json_decode($data, true);

    if ($data['errcode'] == 0) {
        return array('err' => 0, 'msg' => "成功");
    } else {
        return array('err' => 1, 'msg' => $data['errmsg']);
    }
}

/**
 * 发送小程序模板通知消息
 * @param unknown $openid
 * @param unknown $templateid
 * @param unknown $messageBody消息体
 * @return mixed
 */
function wechatSendTemplateMsg($openid, $templateid, $messageBody, $hosp_id, $client)
{

    $tempToken = wechatGetAccessToken($hosp_id, $client);//获取access_token
    if ($tempToken['err']) {
        return array('err' => 1, 'msg' => "access_token为空");
    }
    $access_token = $tempToken['access_token'];
    $formid = wechatGetFormID($openid);
    if (empty($formid)) {
        return array('err' => 1, 'msg' => "formid为空");
    }
    $formwork = '{
         "touser": "' . $openid . '",
         "template_id": "' . $templateid . '",
         "form_id":"' . $formid . '",
         "data": {
           "keyword1": {
             "value": "' . $messageBody['date'] . '",
             "color": "#173177"
         },
         "keyword2": {
             "value":"' . $messageBody['conts'] . '",
             "color": "#173177"
         },
         "keyword3": {
             "value": "' . $messageBody['title'] . '",
             "color": "#173177"
         }
     }
 }';
    // $formwork=$data;
    $url = "https://api.weixin.qq.com/cgi-bin/message/wxopen/template/send?access_token=" . $access_token . "";
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $formwork);
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

/**
 * 获取微信的access_token
 * @return mixed|unknown
 */
function wechatGetAccessToken($hosp_id, $client)
{

    $Config = config('WEIXIN_APP');
    $Config = $Config[$hosp_id];
    if ($client == 1) {
        $Config = $Config['userClient'];
    } else {
        $Config = $Config['doctorClient'];
    }
    $appid = $Config['APPID'];
    $secret = $Config['APPSECRET'];
    $access_token = getCache("wechatToken".$client.$hosp_id);

    if (empty($access_token)) {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . $appid . "&secret=" . $secret . "";
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
        $data = curl_exec($ch);
        curl_close($ch);
        $data = json_decode($data, true);
        if ($data['access_token'])//更新token
        {
            setCache("wechatToken".$client.$hosp_id, $data['access_token'], 7200);
            $access_token = $data['access_token'];
        } else {
            return array('err' => 1, 'msg' => '失败');
        }

    }
    return array('err' => 0, 'access_token' => $access_token);

}

/**
 * 从表中取一个formid来使用
 * @param $openid
 * @param $_hosp
 * @param $ty
 * @return string
 */
function wechatGetFormID($openid, $_hosp, $ty)
{
    $formid = "";
    $totle = 1;
    $infos = \think\Db::query("select * from t_hosp_wechat_formid where hosp_id='" . $_hosp . "' and ty='" . $ty . "' and  openid='" . $openid . "' and num <" . $totle . " order by id desc");
    if ($infos) {
        $info = $infos[0];
        \think\Db::query("update t_hosp_wechat_formid set num=num+1 where  id='" . $info['id'] . "'");
        $formid = $info['formid'];
    }
    return $formid;
}


/**
 * 收集每个用户的微信formid
 * @param unknown $data
 */
function Wx_AddFormID($data)
{

    $sql = generaSql("p_wxformid", $data);
    \think\Db::query($sql);

}

function showStats($stats)
{
    $string = "";

    if (empty($stats)) {
        $string = "<font style='color:red;'>下架</font>";
    } else if ($stats == '1') {
        $string = "<font style='color:green;'>上架</font>";
    }
    return $string;
}


/**
 * 把字符串转成数组
 * @param unknown $string 如：abcd=>['a','b','c','d']
 * @return multitype:
 */
function stringToArr($string)
{
    return str_split($string);

}


/**
 * 格式化一个列表中的一个时间蹉字段
 * @param $lists 列表
 * @param $key 键,单个字段 ctime或者字段数据['ctime']
 * @param string $format
 * @return mixed
 */
function formateTimeForArr($lists, $key, $format = "Y-m-d H:i:s")
{
    if (!is_array($key)) {
        foreach ($lists as $k => $v) {
            if (!empty($key)) {
                if ($v[$key]) {
                    $lists[$k][$key] = formateDate($v[$key], $format);
                }
            }
        }
        return $lists;
    } else {
        return formateTimeForArrs($lists, $key, $format);
    }
}

/**
 * @param $lists 列表
 * @param $keyArr 键数组，即多个键
 * @param string $format
 * @return mixed
 */
function formateTimeForArrs($lists, $keyArr, $format = "Y-m-d H:i:s")
{
    foreach ($lists as $k => $v) {
        foreach ($keyArr as $key => $val) {
            if (!empty($val)) {
                if ($v[$val]) {
                    $lists[$k][$val] = formateDate($v[$val], $format);
                }
            }
        }
    }
    return $lists;
}

function formateDate($time, $format = "Y-m-d H:i:s")
{
    if (empty($time)) {
        return "";
    }
    return date($format, $time);
}

/**
 * 生成字符串二维码
 */
function QrcodeForText($text, $matrixPointSize = 20)
{
    include_once(dirname(realpath(APP_PATH)) . "/vendor/phpqrcode/qrlib.php");
    $errorCorrectionLevel = 'M';
    $time = time();
    $tmpFile = $matrixPointSize . md5($text) . '.png';
    $PNG_TEMP_DIR = "/static/temp/";
    $filename = $PNG_TEMP_DIR . $tmpFile;
    $filenameSave = ROOT_PATH . '/public' . $filename;
    if (file_exists($filenameSave)) {
        return array('err' => 0, 'msg' => '成功', 'data' => array('url' => $filename, 'dir' => $filenameSave));
    }

    $result = QRcode::png($text, $filenameSave, $errorCorrectionLevel, $matrixPointSize, 2);
    if (file_exists($filenameSave)) {
        return array('err' => 0, 'msg' => '成功', 'data' => array('url' => $filename, 'dir' => $filenameSave));
    } else {
        return array('err' => 1, 'msg' => '失败');
    }

}

/**
 * 获取所有用户数据
 * @return Ambigous <string, mixed>
 */
function getAllPeople()
{
    //获取人员
    $sql = "select id,uname,nickname,head,wx_head,parktype,first_depid from p_user order by first_depid asc";
    $userLists = \think\Db::query($sql, []);

    //获取部门
    $sql = "select id,depname from p_dep";
    $depLists = \think\Db::query($sql, []);
    $depLists = changeArrayKey($depLists, 'id');
    foreach ($userLists as $key => $val) {
        $userLists[$key]['depname'] = "";
        if (!empty($depLists[$val['first_depid']])) {
            $userLists[$key]['depname'] = $depLists[$val['first_depid']]['depname'];
        }
    }
    return $userLists;
}


/**
 * 分组获取所有用户数据
 * @return Ambigous <string, mixed>
 */
function getAllPeopleForDep()
{
    //获取人员
    $sql = "select id,uname,nickname,head,wx_head,parktype,first_depid from p_user order by first_depid asc";
    $userLists = \think\Db::query($sql, []);

    //获取部门
    $sql = "select id,depname from p_dep";
    $depLists = \think\Db::query($sql, []);
    $depLists = changeArrayKey($depLists, 'id');
    $depLists[0] = array('id' => 0, 'depname' => '无部门');
    $tempUserList = array();
    foreach ($userLists as $key => $val) {
        $tempUserList[$val['first_depid']][] = $val;
    }
    foreach ($depLists as $key => $val) {
        $depLists[$key]['userList'] = array();
        if ($tempUserList[$val['id']]) {
            $depLists[$key]['userList'] = $tempUserList[$val['id']];
        }
    }
    return $depLists;
}

/**
 * 获取一个空的 stdClass对象
 * @return stdClass
 */
function getMyObj()
{
    return new stdClass();
}

/**
 * 获取一个空的 stdClass对象
 * @return stdClass
 */
function getStdClassObj()
{
    return new stdClass();
}

/**
 * 判断一个变量是否是空，可以是普通类型 也可以是对象类型
 * @param $obj
 * 空返回 true 非空返回 false
 */
function isEmptyForObj($val)
{
    //只能判断普通类型
    if (empty($val)) {
        return true;
    }
    if (is_object($val)) {//判断对象类型
        if (!(array)$val) {
            return true;
        }
    }
    return false;
}


function changeMedalTypeToName($ty)
{
    $list = config('medalType');
    $list = changeArrayKey($list, 'id');
    return $list[$ty]['name'];
}

function getSystemDomain($ty = '')
{
    if ($ty == 'ssl') {
        return $domain = config("DOMAIN_SSL");
    } else {
        return $domain = config("DOMAIN_HTTP");
    }
}


function meetingType($ty)
{
    $all = config("meetingType");
    $name = "";
    foreach ($all as $k => $v) {
        if ($ty == $v['id']) {
            $name = $v['name'];
            break;
        }
    }
    return $name;
}


/*================================================================================================*/
/**生成用户登陆的auth信息
 * @param $array
 * @param string $algorithm
 * @return string
 */
function userAuth($array, $algorithm = 'ecb')
{
    if (empty($array)) {
        return '';
    }
    $data = json_encode($array, true);
    $key = config("auth_key.user_auth_key");
    return encrypt3des($data, $key);
}

function parseuserAuth($auth)
{

    if (!$auth) {
        return array('err' => 1, 'msg' => 'auth信息为空');
    }
    $key = config("auth_key.user_auth_key");
    $temp = decrypt3des($auth, $key);
    $data = json_decode($temp, true);
    if (!empty($data)) {
        return array('err' => 0, 'msg' => '解析成功', 'data' => $data);
    } else {
        return array('err' => 1, 'msg' => '解析失败');
    }
}

function updateuserAuth($auth)
{
    if (empty($auth)) {
        return '';
    }
    $data = parseuserAuth($auth);

    if ($data['err'] != 0) {
        return '';
    }
    $data = $data['data'];
    $data['last_access'] = time();
    $key = config("auth_key.user_auth_key");
    $data = json_encode($data, true);
    return encrypt3des($data, $key);
}

/**
 * 验证登录,成功返回ture,失败返回false
 * @return mixed
 */
function checkLogin($auth)
{
    if (empty($auth)) {
        return false;
    }
    //--解析auth
    $authconfig = parseuserAuth($auth);
    if ($authconfig['err'] != 0) {
        $auth= urldecode($auth);
        $authconfig = parseuserAuth($auth);
        if ($authconfig['err'] != 0) {
            return false;
        }
    }
    $flag = false;
    $sql = "select * from t_user where id={$authconfig['data']['id']} and is_delete=0";
    $info = \think\Db::query($sql, []);
    if (!empty($info)) {
        $flag = true;
    }
    return $flag;
}


/**
 * 判断用户是否登录
 * @param unknown $auth
 */
function checkLoginExp($auth)
{
    if (empty($auth)) {
        return [];
    }
    //--解析auth
    $authconfig = parseuserAuth($auth);

    if ($authconfig['err'] != 0) {
        $auth= urldecode($auth);
        $authconfig = parseuserAuth($auth);
        if ($authconfig['err'] != 0) {
            return [];
        }
    }
    $sql = "select * from t_user where id={$authconfig['data']['id']} and is_delete =0";
    $list = \think\Db::query($sql, []);
    if (!empty($list)) {
        return $list[0];
    } else {
        return [];
    }
}

/**
 * 改变数组的下标为key值
 * @param unknown $list
 * @param unknown $key
 */
function changeKeyForList($list, $key)
{
    if (empty($list)) {
        return array();
    }
    $tempList = array();
    foreach ($list as $k => $v) {
        $tempList[$v[$key]] = $v;
    }
    return $tempList;
}

function sendPhoneMsg($phone)
{


    $config = config("WANGYI_PHONE_MSG");
    $AppKey = $config['AppKey'];
    $AppSecret = $config['AppSecret'];
    $templateid = $config['templateid'];
    include_once(dirname(realpath(APP_PATH)) . "/vendor/msg/ServerAPI.php");
    $p = new \ServerAPI($AppKey, $AppSecret, 'curl');     //fsockopen伪造请求
    return $p->sendSmsCode($templateid, $phone, '', '4');
}


function tengxunPhoneSend($phone, $code)
{
    include_once(dirname(realpath(APP_PATH)) . "/vendor/qq_qcloudsms/src/index.php");

    // 短信应用SDK AppID
    $appid = 1400445811; // 1400开头
    // 短信应用SDK AppKey
    $appkey = "0823cccc97fa975af04ac68a5436b466";
    // 短信模板ID，需要在短信应用中申请
    $templateId = 767838; // NOTE: 这里的模板ID`7839`只是一个示例，真实的模板ID需要在短信控制台中申请
    // 签名
    $smsSign = "四川奥洁"; // NOTE: 这里的签名只是示例，请使用真实的已申请的签名，签名参数使用的是`签名内容`，而不是`签名ID`
    // 单发短信
    try {
        $ssender = new Qcloud\Sms\SmsSingleSender($appid, $appkey);
//        $result = $ssender->send(0, "86", $phone, "【" . $smsSign . "】您的验证码为" . $code . "，请勿告诉他人！", "", "");
        $result = $ssender->send(0, "86", $phone, "【" . $smsSign . "】验证码为：" . $code . "，若非本人操作，请勿泄露。", "", "");
        $rsp = json_decode($result);

        if ($rsp->result == 0 && $rsp->errmsg == 'OK') {
            return true;
        } else {
            return false;
        }
    } catch (\Exception $e) {
        return false;
    }
}

/**
 * 支付宝支付接口
 */
function alipay_pay($order_sn, $money, $notifyurl = "http://api.ituike.net:91/api/order/alipay_n", $title = "购买课程")
{
    $config = config("alipayConfig");
    include_once(dirname(realpath(APP_PATH)) . "/vendor/alipay_sdk_zhifu/AopSdk.php");
    $aop = new AopClient;
    $aop->gatewayUrl = "https://openapi.alipay.com/gateway.do";
    $aop->charset = "utf-8";
    $aop->appId = $config['appId'];
    $aop->rsaPrivateKey = $config['rsaPrivateKey'];
    //     $aop->format='json';

    $aop->signType = $config['signType'];

    $aop->alipayrsaPublicKey = $config['alipayrsaPublicKey'];
    //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
    $request = new AlipayTradeAppPayRequest();
    $bizcontent = "{" .
        "\"timeout_express\":\"30m\"," .
        "\"product_code\":\"QUICK_MSECURITY_PAY\"," .
        "\"total_amount\":{$money}," .
        "\"subject\":\"{$title}\"," .
        "\"body\":\"{$title}\"," .
        "\"out_trade_no\":\"{$order_sn}\"" .
        "  }";
    $time = date("Y-m-d H:i:s");
    $request->setBizContent($bizcontent);
    $request->setNotifyUrl($notifyurl);
    //这里和普通的接口调用不同，使用的是sdkExecute
    $sign = $aop->sdkExecuteSign($request, $time);
    $sign = urlencode($sign);
    return 'charset=utf-8&biz_content=' . $bizcontent . '&method=alipay.trade.app.pay&app_id=' . $config['appId'] . '&sign_type=' . $config['signType'] . '&version=1.0&timestamp=' . $time . '&notify_url=' . $notifyurl . '&sign=' . $sign;
}

/**
 * 支付宝验证接口
 * @return bool
 */
function alipay_notify_check()
{
    $config = config("alipayConfig");
    include_once(dirname(realpath(APP_PATH)) . "/vendor/alipay_sdk_zhifu/AopSdk.php");
    $aop = new AopClient;
    $aop->alipayrsaPublicKey = $config['alipayrsaPublicKey'];
    $flag = $aop->rsaCheckV1($_POST, NULL, $config['signType']);
    return $flag;
}

function build_order_no($pre='')
{
    return $pre.date('Ymd') . substr(implode(NULL, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
}

/**
 * 对一个小数，保留N位小数，四舍五入 函数
 * @param $money 原始数据
 * @param int $num 保留位数
 * @return float
 */
function rounding($money, $num = 2)
{
    return round($money, $num);
}

/**
 * 对一个小数，保留N位小数，不做四舍五入 函数
 * @param $money
 * @param int $num
 */
function roundingE($money, $num = 2)
{
    $num = $num + 1;
    if ($num <= 0) {
        return floor($money);
    } else {
        return substr(sprintf("%.{$num}f", $money), 0, -1);
    }
}

/**
 * 格式化一个列表中的时间蹉 字段为指定时间格式
 * @param $list 列表
 * @param string $field 需要格式化的时间蹉字段名称
 * @param string $format 格式化规则
 * @return array
 */
function formatTimeForList($list, $field = "ctime", $format = "Y-m-d H:i:s")
{
    if (empty($list)) {
        return array();
    }
    foreach ($list as $key => $val) {
        if ($val[$field]) {
            $list[$key][$field] = date($format, $val[$field]);
        } else {
            $list[$key][$field] = "";
        }
    }
    return $list;
}

/**
 * 检查手机号是否正确
 * @param $phonenumber
 * @return  true手机号正确 false手机号不正确
 */
function checkPhone($phonenumber)
{
    if (empty($phonenumber)) {
        return false;
    }
    if (preg_match("/^1[3456789]{1}\d{9}$/", $phonenumber)) {
        return true;
    } else {
        return false;
    }
}

/**
 * 支付宝转账
 * @param $order_sn 订单号
 * @param $zfb_account 支付宝账号
 * @param $zfb_bname 支付宝名称
 * @param $money 转账金额
 * @return array
 * @throws Exception
 */
function alipayTransferAccounts($order_sn, $zfb_account, $zfb_bname, $money)
{
    $config = config("alipayConfig");
    include_once(dirname(realpath(APP_PATH)) . "/vendor/alipay/AopSdk.php");
    $aop = new \AopClient ();
    $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';
    $aop->appId = $config['appId'];
    $aop->apiVersion = '1.0';
    $aop->signType = $config['signType'];
    $aop->postCharset = 'UTF-8';
    $aop->format = 'json';
    $aop->rsaPrivateKey = $config['rsaPrivateKey'];
    $aop->alipayrsaPublicKey = $config['alipayrsaPublicKey'];

    $request = new \AlipayFundTransToaccountTransferRequest ();
    $requestData = array(
        "out_biz_no" => $order_sn,
        "payee_type" => "ALIPAY_LOGONID",
        "payee_account" => $zfb_account,
        "amount" => $money,
        "payer_show_name" => "懂睡眠APP",
        "payee_real_name" => $zfb_bname,
        "remark" => '余额提现',
    );
    $request->setBizContent(json_encode($requestData, true));
    $result = $aop->execute($request);
    $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";
    $resultCode = $result->$responseNode->code;
    if (!empty($resultCode) && $resultCode == 10000) {
        return array('err' => 0, 'msg' => $result->$responseNode->msg, 'order_id' => $result->$responseNode->order_id, 'out_biz_no' => $result->$responseNode->out_biz_no);
    } else {

        return array('err' => 1, 'msg' => $result->$responseNode->msg, 'sub_msg' => $result->$responseNode->sub_msg);
    }
}

/**
 * 获取文件后缀
 * @param $file
 * @return mixed
 */
function getSuffixForFile($file)
{
    $arr = explode('.', $file);
    $suffix = end($arr);
    return strtolower($suffix);
}

/**
 * @param $path原始文件
 * @param string $copy 生成文件
 * eg /static/abc.jpg =>/static/abc_1.jpg
 */
function generaCopyFileName($path, $copy = "1")
{
    $temp = explode(".", $path);
    return $temp[0] . "_" . $copy . "." . $temp[1];
}


function str_rand($length = 7, $char = '123456789abcdefghijkmnpqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ')
{
    if (!is_int($length) || $length < 0) {
        return false;
    }
    $string = '';
    for ($i = $length; $i > 0; $i--) {
        $string .= $char[mt_rand(0, strlen($char) - 1)];
    }
    return $string;
}

/**
 * 解析系统函数的路径 和功能
 * @param $path  eg \app\task\controller\Sleepreport#taskloadcurves
 * @return array eg: array('\app\task\controller\Sleepreport','taskloadcurves')
 */
function parseNamespacePath($path)
{
    $temp = explode("#", $path);
    if (empty($temp)) {
        return array();
    }
    if (empty($temp[0])) {
        return array();
    }
    if (empty($temp[1])) {
        $temp[1] = "task";
    }
    return array($temp[0], $temp[1]);
}

/**
 * 根据varname获取系统配置里面的值
 */
function getSystemConfigForVarname($varname = "")
{
    if (empty($varname)) {
        return '';
    }
    $sql = "select id,varname,varvalue,info from t_sysconfig where varname ='{$varname}'";
    $list = \think\Db::query($sql);
    if (empty($list)) {
        return '';
    }
    return $list[0]['varvalue'];
}


/**
 * 根据所有系统配置
 */
function getAllSystemConfig()
{
    $sql = "select id,varname,varvalue,info from t_sysconfig";
    $list = \think\Db::query($sql);
    if (empty($list)) {
        return array();
    }
    $result = array();
    foreach ($list as $key => $val) {
        $result[$val['varname']] = $val['varvalue'];
    }
    return $result;
}

/**
 * 应用范围 从数据库中查询列表  安装in里面的顺序排序
 * 从数据库中 id in(3,2,1)查询出来的值，按(3,2,1)排序
 * @param $lists 二维数组
 * @param $ids 1,5,4,3,2
 */
function listsForSorts($lists, $ids)
{
    $newids = explode(",", $ids);
    $tempArray = array();
    $newList = changeKeyForList($lists, 'id');
    foreach ($newids as $key => $val) {
        if (!empty($newList[$val])) {
            $tempArray[] = $newList[$val];
        }
    }
    return $tempArray;
}

/**
 * 监听钩子函数
 * @param $tag
 * @param null $params
 */
function tag($tag, $params = NULL)
{
    \think\Hook::listen($tag, $params);
}


function recordClientVerAndType($userInfo, $os = "", $ver = "")
{
    if (empty($os)) {
        $os = "";
    }
    if (empty($ver)) {
        $ver = "";
    }
    if ($ver && $os) {
        $sql = "update t_user set _os='" . $os . "',_ver ='" . $ver . "',_last_login_time='" . date('Y-m-d H:i:s') . "' where id='" . $userInfo['id'] . "'";
        \think\Db::query($sql);
    }
}


/**
 * 微信小程序支付回调xml 和数组 解析函数
 * @param $arr
 * @param int $level
 * @return null|string|string[]
 */
function array2xml($arr, $level = 1)
{

    $s = $level == 1 ? "<xml>" : '';
    foreach ($arr as $tagname => $value) {

        if (is_numeric($tagname)) {
            $tagname = $value['TagName'];
            unset($value['TagName']);
        }

        if (!is_array($value)) {

            $s .= "<{$tagname}>" . (!is_numeric($value) ? '<![CDATA[' : '') . $value . (!is_numeric($value) ? ']]>' : '') . "</{$tagname}>";
        } else {
            $s .= "<{$tagname}>" . array2xml($value, $level + 1) . "</{$tagname}>";
        }
    }

    $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
    return $level == 1 ? $s . "</xml>" : $s;
}

function xml2array($xml)
{
    if (empty($xml)) {
        return array();
    }
    $result = array();
    $xmlobj = isimplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA);
    if ($xmlobj instanceof SimpleXMLElement) {
        $result = json_decode(json_encode($xmlobj), true);
        if (is_array($result)) {
            return $result;
        } else {
            return '';
        }
    } else {
        return $result;
    }
}

/**
 * 微信小程序支付 回调解析函数
 * @param $string
 * @param string $class_name
 * @param int $options
 * @param string $ns
 * @param bool $is_prefix
 * @return bool|SimpleXMLElement
 */
function isimplexml_load_string($string, $class_name = 'SimpleXMLElement', $options = 0, $ns = '', $is_prefix = false)
{
    libxml_disable_entity_loader(true);
    if (preg_match('/(\<\!DOCTYPE|\<\!ENTITY)/i', $string)) {
        return false;
    }
    return simplexml_load_string($string, $class_name, $options, $ns, $is_prefix);
}


/**
 * 微信支付 生成随机字符串
 * 产生随机字符串，不长于32位
 * @param int $length
 * @return 产生的随机字符串
 */
function getWechatNonceStr($length = 32)
{
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str = "";
    for ($i = 0; $i < $length; $i++) {
        $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
    }
    return $str;
}

/**
 * 获取微信支付签名
 * 生成签名
 * @return 签名
 */
function getWechatMakeSign($data, $key)
{
    $data = array_filter($data);
    //签名步骤一：按字典序排序参数
    ksort($data);
    $string_a = http_build_query($data);
    $string_a = urldecode($string_a);
    //签名步骤二：在string后加入KEY
    //$config=$this->config;
    $string_sign_temp = $string_a . "&key=" . $key;
    //签名步骤三：MD5加密
    $sign = md5($string_sign_temp);
    // 签名步骤四：所有字符转为大写
    $result = strtoupper($sign);
    return $result;
}

/**
 * 二维数组按照指定指定排序
 * @param $array 要排序的二维数组
 * @param $keys 要排序的字段
 * @param string $sort 升序 还是降序
 * @return array 返回新的数组
 */
function twoArraySort($array,$keys,$sort='asc') {
    $newArr = $valArr = array();
    foreach ($array as $key=>$value) {
        $valArr[$key] = $value[$keys];
    }
    ($sort == 'asc') ?  asort($valArr) : arsort($valArr);
    reset($valArr);
    foreach($valArr as $key=>$value) {
        $newArr[$key] = $array[$key];
    }
    return $newArr;
}

function getNewWindProductClass(){
    $data=array(
        array (
            'id' => 1,
            'name' => '空气净化器'
        ),
        array (
            'id' =>2,
            'name' => '空气消毒机'
        ),
        array (
            'id' => 3,
            'name' => '床单位消毒机'
        ),
        array (
            'id' => 4,
            'name' => '油烟净化器'
        ),
        array (
            'id' => 5,
            'name' => '果蔬净化机'
        ),
    );
    return $data;
}

error_reporting(E_ERROR | E_WARNING | E_PARSE);



